package cn.wf.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @Description  这里是验证token不为空，就是每个url后面必须带上token=xxx,否则响应不通过，返回401(权限不足)
 * @Author 万飞
 * @Date 2018/8/19 0:57
 */
@Component
public class TokenFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return PRE_TYPE;  //前置过滤器
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;  //PRE_DECORATION_FILTER_ORDER=5 是过滤器优先级，越小的越靠前， - 1是在该过滤器优先级前
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }  //false不校验

    /**
     * 实现的逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        //这里从url参数获取，也可以从cookie，helder里获取
        String token = request.getParameter("token");
        if (StringUtils.isBlank(token)) {
            requestContext.setSendZuulResponse(false);  //不通过
            requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);  //401一般表示权限不足
        }
        return null;
    }
}
